package com.iqunxing.redis.redisInAction.ch04;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class ItemService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean listItem(final String itemId, final String sellerId, final double price) {
        final String inventory = "inventory:" + sellerId;
        final String item = itemId + '.' + sellerId;
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            redisTemplate.watch(inventory);
            Boolean exists = redisTemplate.boundSetOps(inventory).isMember(itemId);
            if (!exists) {
                redisTemplate.unwatch();
                return false;
            }
            List<Object> txResults = redisTemplate.executePipelined(new SessionCallback<List<String>>() {

                @Override
                public List<Object> execute(RedisOperations ops) throws DataAccessException {
                    ops.boundZSetOps("market:").add(item, price);
                    ops.boundSetOps(inventory).remove(itemId);
                    return ops.exec();
                }

            });
            if (txResults == null) {
                continue;
            }
            return true;
        }
        return false;
    }

}
